<?php
declare(strict_types=1);

namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\Order as OrderModel;
use think\Exception;
use think\facade\Cache;

class Order extends BusiBase
{
    public function __construct()
    {
        $this->model = new OrderModel();
    }

    /**
     * 提交订单处理
     *
     * @param array $data
     * @return bool
     * @throws \think\Exception
     */
    public function addOrder(array $data)
    {
        // 生成当前订单号
        $orderId = Str::getWorkOrderId();

        // 获取当前订单数据数组
        $cart    = new Cart();
        $lists   = $cart->lists($data['user_id'], $data['ids']);
        if (!$lists) return false;

        $skuIdArr = array_column($lists, 'num', 'id');
        $goodsArr = array_column($lists, 'num', 'goods_id');

        // 生成订单表数据部分
        $orderData = [
            'user_id' => $data['user_id'],
            'order_id' => $orderId,
            'total_price' => array_sum(array_column($lists, 'total_price')),
            'address_id'  => $data['address_id'],
        ];
        // 生成订单商品表数据
        $orderGoodsData = array_map(function($data) use($orderId) {
            $data['sku_id'] = $data['id'];
            unset($data['id']);
            $data['order_id'] = $orderId;
            return $data;
        }, $lists);

        // 开启事务
        $this->model->startTrans();
        try {
            // 订单数据新增
            $order_id = $this->insert($orderData);
            if (!$order_id) return false;
            // 批量添加 order_goods 表订单商品数据
            $orderGoods = new OrderGoods();
            $order_goods_ids = $orderGoods->addAll($orderGoodsData);
            if (!$order_goods_ids) return false;
            // 批量修改 goods_sku 表订单商品库存
            $goodsSku = new GoodsSku();
            $update_sku_stock = $goodsSku->updateMoreStock($skuIdArr);
            if (!$update_sku_stock) return false;
            // 修改 goods 表商品库存
            $update_goods_stock = (new Goods())->updateMoreStock($goodsArr);
            if (!$update_goods_stock) return false;
            // 提交事务
            $this->model->commit();
            // 删除购物车数据
            $deleteCart = $cart->deleteRdis($data['user_id'], array_keys($skuIdArr));
            if (!$deleteCart) return false;
            try {
                Cache::zAdd(config('redis.order.status_key'), Time::orderInvalidTime(), $orderId);
            } catch (\Exception $e) {
                throw new Exception('添加延迟队列失败');
            }
            return ['id' => $orderId];
        } catch (\Exception $e) {
            // 事务回滚
            $this->model->rollback();
            $this->errorLog('add order '.json_encode($data).' error: '.$e->getMessage());
            return false;
        }
    }

    /**
     * 根据订单 id 获取订单信息
     *
     * @param array $data
     * @return array|mixed
     */
    public function getOrderByOrderId(array $data)
    {
        // 获取订单表信息
        try {
            $orderRes = $this->model->getDataByCondition($data);
        } catch (\Exception $e) {
            $this->errorLog('ger normal data by condition error: '.$e->getMessage());
            return [];
        }
        if (!$orderRes) return [];
        $orderRes = $orderRes->toArray();
        $orderData = $orderRes[0];
        $orderData['id'] = $data['order_id'];

        // 查找地址信息
        $address   = new Address();
        $addData   = $address->getById((int) $orderData['address_id']);
        if (!$addData) return [];
        $orderData['consignee_info'] = "{$addData['sheng']} {$addData['shi']} {$addData['qu']} {$addData['more']} {$addData['name']} 收 {$addData['mobile']}{$addData['phone']}";
        // 获取订单商品信息
        $orderGoods = new OrderGoods();
        $orderGoodsRes = $orderGoods->getDataByCondition((int) $data['order_id']);
        $orderData['malls'] = $orderGoodsRes;
        return $orderData;
    }
}